<template>
  <el-breadcrumb :separator-icon="ArrowRight">
    <el-breadcrumb-item :to="{ path: '/' }">首页(登录)</el-breadcrumb-item>
    <el-breadcrumb-item>门诊</el-breadcrumb-item>
    <el-breadcrumb-item>退款记录</el-breadcrumb-item>
  </el-breadcrumb>

  <div>
    <!-- 标题和工具栏 -->
    <el-card style="margin-top: 10px;">
      <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
        <div style="display: flex; align-items: center;">
          <el-icon :size="20" style="margin-right: 8px; color: #f56c6c;">
            <RefreshLeft />
          </el-icon>
          <span style="font-size: 18px; font-weight: 600; color: #303133;">退款记录</span>
        </div>
        <div>
          <el-button type="primary" plain>导入</el-button>
          <el-button type="primary">导出</el-button>
        </div>
      </div>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="search" class="demo-form-inline">
        <el-form-item>
          <el-date-picker
            v-model="search.dateRange"
            type="daterange"
            range-separator="~"
            start-placeholder="请选择日期"
            end-placeholder="请选择日期"
            value-format="YYYY-MM-DD"
            unlink-panels
            clearable
            style="width: 340px;"
          />
        </el-form-item>
        <el-form-item>
          <el-input 
            v-model="search.keyword" 
            placeholder="请输入病人姓名/就诊卡号" 
            clearable 
            style="width: 240px;" 
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表 -->
    <el-card style="margin-top: 10px;">
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="operatingTime" label="操作时间" width="170" align="center" />
        <el-table-column prop="operatingNum" label="退款编号" width="160" align="center" />
        <el-table-column prop="name" label="患者姓名" width="100" align="center" />
        <el-table-column prop="medicalCard" label="就诊卡号" width="120" align="center" />
        <el-table-column prop="source" label="来源" width="120" align="center" />
        <el-table-column prop="businessName" label="业务类型" width="120" align="center" />
        <el-table-column prop="paymentMethod" label="退款方式" width="100" align="center" />
        <el-table-column prop="paymentAmount" label="退款金额（元）" width="130" align="center">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: 500;">{{ row.paymentAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentStatus" label="退款状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag type="success" v-if="row.paymentStatus === 1">已退款</el-tag>
            <el-tag type="info" v-else>未退款</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="卡内余额" width="110" align="center">
          <template #default="{ row }">
            <span style="color: #67c23a; font-weight: 500;">{{ row.balance }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              :icon="Document" 
              circle 
              @click="handleRefund(row)"
              :disabled="row.paymentStatus === 1"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
     <div>
        <el-pagination
          v-model:current-page="page.PageIndex"
          v-model:page-size="page.PageSize"
          :page-sizes="[5, 10,15, 20]"
          prev-text="上一页" 
          next-text="下一页"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalCount"
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 确认退款弹窗 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="确认退款"
      width="400px"
      :before-close="handleCloseDialog"
    >
      <div style="text-align: center; padding: 20px 0;">
        <el-icon :size="48" style="color: #f56c6c; margin-bottom: 16px;">
          <Warning />
        </el-icon>
        <p style="font-size: 16px; margin-bottom: 8px;">确认要退款给患者 <strong>{{ currentRefundRecord?.name }}</strong> 吗？</p>
        <p style="color: #909399; font-size: 14px;">退款金额：<span style="color: #f56c6c; font-weight: 500;">{{ currentRefundRecord?.paymentAmount }}元</span></p>
      </div>
      <template #footer>
        <div style="text-align: center;">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRefund" :loading="refundLoading">确认退款</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { ArrowRight, RefreshLeft, Document, Warning } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dataRead, dataWrite } from '@/Utils/Http'

interface PageState {
  PageIndex: number
  PageSize: number
  totalCount: number
  pageCount: number
}

interface SearchForm {
  dateRange: string[]
  keyword: string
}

const loading = ref(false)
const jumpPage = ref('')
const refundDialogVisible = ref(false)
const refundLoading = ref(false)
const currentRefundRecord = ref<any>(null)

const page = reactive<PageState>({ 
  PageIndex: 1, 
  PageSize: 10, 
  totalCount: 0,
  pageCount: 0
})

const search = reactive<SearchForm>({
  dateRange: [],
  keyword: ''
})

const tableData = ref<any[]>([])

// 搜索
const handleSearch = () => {
  page.PageIndex = 1
  getTableData()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  page.PageSize = val
  page.PageIndex = 1
  getTableData()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  page.PageIndex = val
  getTableData()
}

// 跳转页面
const handleJumpPage = () => {
  const pageNum = parseInt(jumpPage.value)
  if (pageNum > 0 && pageNum <= page.pageCount) {
    page.PageIndex = pageNum
    getTableData()
    jumpPage.value = ''
  } else {
    ElMessage.warning('请输入有效的页码')
  }
}
watch(page,()=>{
  getTableData()
})
// 获取表格数据
const getTableData = () => {
  dataRead.get('/BaseData/AmountQuery?BusinessId=6', { 
    params:{
       PageIndex: page.PageIndex,
        PageSize: page.PageSize,
    }
   })
    .then((res) => {
      if (res.data.code === 200) {
        tableData.value = res.data.data.data
        page.totalCount = res.data.data.totalCount
        page.pageCount = res.data.data.pageCount
      }
    })
    .catch(() => {
      ElMessage.error('获取数据失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 处理退款操作
const handleRefund = (row: any) => {
  if (row.paymentStatus === 1) {
    ElMessage.warning('该记录已退款，无法重复操作')
    return
  }
  console.log('退款记录数据:', row) // 调试信息
  currentRefundRecord.value = row
  refundDialogVisible.value = true
}

// 关闭弹窗
const handleCloseDialog = () => {
  refundDialogVisible.value = false
  currentRefundRecord.value = null
}

// 确认退款
const confirmRefund = async () => {
  if (!currentRefundRecord.value) return
  
  refundLoading.value = true
  try {
    // 尝试不同的ID字段名
    const amountId = currentRefundRecord.value.id || 
                    currentRefundRecord.value.amountId || 
                    currentRefundRecord.value.operatingNum ||
                    currentRefundRecord.value.paymentId
    
    console.log('发送退款请求，完整记录:', currentRefundRecord.value) // 调试信息
    console.log('使用的amountId:', amountId) // 调试信息
    
    const response = await dataWrite.post('/Amount/UpdAmountStatus', {
      amountId: amountId
    })
    
    console.log('退款API响应:', response.data) // 调试信息
    
    if (response.data.code === 400 && response.data.message === '修改成功') {
      ElMessage.success('退款成功')
      
      // 直接更新当前记录的状态（因为currentRefundRecord是tableData中某一行的引用）
      currentRefundRecord.value.paymentStatus = 1
      
      refundDialogVisible.value = false
      currentRefundRecord.value = null
    } else {
      ElMessage.error(response.data.message || '退款失败')
    }
  } catch (error: any) {
    console.error('退款失败详情:', error)
    if (error.response) {
      console.error('响应状态:', error.response.status)
      console.error('响应数据:', error.response.data)
      ElMessage.error(`退款操作失败: ${error.response.data?.message || error.message}`)
    } else {
      ElMessage.error('网络错误，请检查连接')
    }
  } finally {
    refundLoading.value = false
  }
}

onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.demo-form-inline {
  margin-top: 8px;
}

:deep(.el-card) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-pagination) {
  font-weight: 400;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409eff;
  color: #fff;
}
</style>

